package com.my.lucky7.service;

import cn.hutool.core.util.StrUtil;
import com.my.lucky7.common.ApiResult;
import com.my.lucky7.config.IndexImageConfig;
import com.my.lucky7.dao.GalleryImageRepository;
import com.my.lucky7.entity.GalleryImage;
import com.my.lucky7.entity.IndexImageData;
import com.my.lucky7.upload.AliyunOSSImageUploader;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
public class GalleryImageService {
    private final GalleryImageRepository repository;

    @Resource(name = "aliyunOSSImageUploader")
    AliyunOSSImageUploader aliyunOSSImageUploader;

    @Resource(name = "indexImageConfig")
    IndexImageConfig indexImageConfig;

    public GalleryImageService(GalleryImageRepository repository) {
        this.repository = repository;
    }

    public GalleryImage createImage(GalleryImage image) {
        // 解析fileName,https://luck7-gallery.oss-cn-beijing.aliyuncs.com/luck7-gallery/gallery/2.png
        if(StringUtils.isEmpty(image.getBucketName())){
            image.setBucketName(aliyunOSSImageUploader.BUCKET_NAME);
        }
        if(StringUtils.isEmpty(image.getObjectName())){
            image.setObjectName(StrUtil.subAfter(image.getUrl(), aliyunOSSImageUploader.BUCKET_NAME + "/", true));
        }
        // 填充buckeName
        return repository.save(image);
    }

    public List<GalleryImage> getAllImages() {
        List<GalleryImage> galleryImages = repository.findAll();
        // 拼接生成临时访问链接
        for (GalleryImage image : galleryImages) {
            // 生成临时访问链接
            String tempUrl = aliyunOSSImageUploader.generateTempUrl(image.getBucketName(), image.getObjectName(), 10);
            // 将临时访问链接添加到图片对象中
            image.setUrl(tempUrl);
        }
        return galleryImages;
    }

    public GalleryImage getImageByDesc(String desc) {
        List<GalleryImage> byDesc = repository.findByDesc(desc);
        if(!CollectionUtils.isEmpty(byDesc)){
            // 更新缩放比例
            byDesc.get(0).setUrl(aliyunOSSImageUploader.generateTempUrl(byDesc.get(0).getBucketName(), byDesc.get(0).getObjectName(), 30));
            return byDesc.get(0);
        }
        return null;
    }

    public Optional<GalleryImage> getImageById(Integer id) {
        return repository.findById(id);
    }

    public GalleryImage updateImage(Integer id, GalleryImage updatedImage) {
        return repository.findById(id)
                .map(existing -> {
                    existing.setUrl(updatedImage.getUrl());
                    existing.setDescription(updatedImage.getDescription());
                    existing.setCategory(updatedImage.getCategory());
                    existing.setCategories(updatedImage.getCategories());
                    return repository.save(existing);
                })
                .orElseThrow(() -> new RuntimeException("Image not found"));
    }

    public void deleteImage(Integer id) {
        repository.deleteById(id);
    }

    public ApiResult getIndexImage() {
        Map<String, Object> resultMap = new HashMap<>();
        List<String> avatarImages = indexImageConfig.getAvatarImages();
        List<IndexImageData> avatarImageDatas = new ArrayList<>();
        List<String> slideImages = indexImageConfig.getSlideImages();
        List<IndexImageData> slideImageDatas = new ArrayList<>();
        if(!CollectionUtils.isEmpty(slideImages)){
            // 原始链接替换为临时链接
            for (int i = 0; i < slideImages.size(); i++) {
                String slideImage = slideImages.get(i);
                // 生成临时访问链接
                String tempUrl = aliyunOSSImageUploader.generateTempUrl(aliyunOSSImageUploader.BUCKET_NAME, slideImage, 30);
                slideImageDatas.add(new IndexImageData(tempUrl, ""));
            }
        }
        if(!CollectionUtils.isEmpty(avatarImages)){
            for (int i = 0; i < avatarImages.size(); i++) {
                String avatarImage = avatarImages.get(i);
                // 原始链接替换为临时链接
                String tempUrl = aliyunOSSImageUploader.generateTempUrl(aliyunOSSImageUploader.BUCKET_NAME, avatarImage, 10);
                avatarImageDatas.add(new IndexImageData(tempUrl, ""));
            }
        }
        resultMap.put("avatars", avatarImageDatas);
        resultMap.put("slides", slideImageDatas);
        return ApiResult.success(resultMap);
    }
}